/**
 *   This file is part of Java Simple Sampler.
 *
 *   Java Simple Sampler is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License.
 *
 *   Java Simple Sampler is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Java Simple Sampler.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   @author David Lapetina	
 */
package net.onirik.mao.sampler.sound;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.SourceDataLine;

public class WavSamplePlayer implements SamplePlayer {
	private File soundFile;

	private AudioInputStream audioInputStream = null;

	private static SourceDataLine auline = null;

	private byte[] file = null;

	private int length;

	private boolean playing = false;

	public WavSamplePlayer(String fileName) {
		soundFile = new File(fileName);
		if (!soundFile.exists()) {
			throw new IllegalArgumentException(new FileNotFoundException());
		}
		audioInputStream = AudioHelper.SINGLETON.getAudioInputStream(soundFile);

		auline = AudioHelper.SINGLETON.getSourceDataLine();
		try {
			file = new byte[(int) soundFile.length()];
			length = audioInputStream.read(file, 0, file.length);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	public void play() {
		this.playing = true;
		ByteArrayInputStream bis = new ByteArrayInputStream(this.file);
		int bufferSize = AudioHelper.SINGLETON.getAudioFormat().getFrameSize()
				* Math.round(AudioHelper.SINGLETON.getAudioFormat()
						.getSampleRate() / 100);
		byte[] buffer = new byte[bufferSize];
		int numBytesRead = 0;
		while (numBytesRead != -1 && this.playing) {
			numBytesRead = bis.read(buffer, 0, buffer.length);
			if (numBytesRead != -1)
				auline.write(buffer, 0, numBytesRead);
		}
	}

	public void stop() {
		this.playing = false;
	}

	public String getResourceName() {
		return this.soundFile.getName();
	}

	public String getResourcePath() {
		return this.soundFile.getParent();
	}
}
